<template>
  <view class="home">
    <!-- HBuilder轮播图组件 -->
    <swiper
      class="banner-swiper"
      :indicator-dots="true"
      :circular="true"
      indicator-color="#fff"
      :autoplay="true"
      :interval="3000"
      :duration="500"
    >
      <swiper-item v-for="(item, index) in swiperList" :key="index || 'default'">
        <view class="swiper-item" @click="handleBannerClick(item)">
          <image :src="item.image" mode="aspectFill" class="swiper-image" />
          <!-- <text v-if="item.title" class="swiper-title">{{ item.title }}</text> -->
        </view>
      </swiper-item>
    </swiper>
    <!-- 快捷导航 -->
    <view v-if="navList.length > 0">
      <wd-grid clickable :column="4" class="mt-2">
        <wd-grid-item
          v-for="item in navList"
          :key="item.id || item.title"
          use-slot
          link-type="navigateTo"
          :url="item.url"
        >
          <view class="p-2 relative">
            <image
              class="w-120rpx h-120rpx rounded-8rpx"
              :src="item.icon"
              mode="aspectFill"
              loading="lazy"
              show-menu-by-longpress="false"
              @load="onImageLoad(item.id)"
              @error="onImageError(item.id)"
            />
            <!-- 图片加载前的占位骨架屏 -->
            <view
              v-if="loadingImages.includes(item.id)"
              class="image-skeleton w-120rpx h-120rpx rounded-8rpx bg-gray-100 absolute top-2 left-2"
            ></view>
          </view>
          <wd-text class="text" color="#101010" bold :text="item.title"></wd-text>
        </wd-grid-item>
      </wd-grid>
    </view>
    <!-- 导航列表空状态 -->
    <view v-else class="nav-empty">
      <!-- <image class="w-320rpx h-320rpx mx-auto opacity-50" src="/static/icons/loading.png" /> -->
      <text class="block text-center mt-4 text-gray-400">加载导航数据中...</text>
    </view>

    <!-- 通知公告 -->
    <wd-notice-bar
      text="欢迎使用数字家谱系统，您可以在这里管理您的家族信息，查看家谱树，添加家族成员等。"
      color="#34D19D"
      type="info"
    >
      <template #prefix>
        <wd-tag color="#FAA21E" bg-color="#FAA21E" plain custom-style="margin-right:10rpx">
          通知公告
        </wd-tag>
      </template>
    </wd-notice-bar>

    <!-- 数据统计 -->
    <!-- <wd-grid :column="2" :gutter="2">
      <wd-grid-item use-slot custom-class="custom-item">
        <view class="flex justify-start pl-5">
          <view class="flex-center">
            <image class="w-80rpx h-80rpx rounded-8rpx" src="/static/icons/family.png" />
            <view class="ml-5 text-left">
              <view class="font-bold">家族数</view>
              <view class="mt-2">{{ familyStats.familyCount }}</view>
            </view>
          </view>
        </view>
      </wd-grid-item>
      <wd-grid-item use-slot custom-class="custom-item">
        <view class="flex justify-start pl-5">
          <view class="flex-center">
            <image class="w-80rpx h-80rpx rounded-8rpx" src="/static/icons/member.png" />
            <view class="ml-5 text-left">
              <view class="font-bold">成员数</view>
              <view class="mt-2">{{ familyStats.memberCount }}</view>
            </view>
          </view>
        </view>
      </wd-grid-item>
    </wd-grid> -->

    <!-- 最新文化内容 -->
    <wd-card>
      <template #title>
        <view class="flex-between">
          <view class="card-title">最新文化内容</view>
          <view>
            <wd-button type="primary" size="small" class="view-all-btn" @click="navigateToCulture">
              查看全部
            </wd-button>
          </view>
        </view>
      </template>

      <view class="content-list">
        <view
          v-for="(content, index) in cultureContents"
          :key="index"
          class="content-item"
          @click="navigateToCultureDetail(content.id)"
        >
          <view class="content-info">
            <view class="content-title text-ellipsis">{{ content.title }}</view>
            <view class="content-desc text-ellipsis-2">{{ content.content }}</view>
            <view class="content-meta">
              <text class="author">作者: {{ content.author }}</text>
              <!-- <text class="view-count">阅读量: {{ content.viewCount }}</text> -->
            </view>
          </view>
        </view>
      </view>
    </wd-card>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import CultureAPI, { CultureContentItem } from "@/api/culture";

import PositionContentAPI from "@/api/genealogy/position_content";

const familyStats = ref({
  familyCount: 0,
  memberCount: 0,
});

const cultureContents = ref<CultureContentItem[]>([]);

interface SwiperItem {
  id?: string;
  image: string;
  link?: string;
  title?: string;
}

const swiperList = ref<SwiperItem[]>([]);

// 快捷导航列表
const navList = reactive([] as NavItem[]);

interface NavItem {
  id?: string;
  icon: string;
  title: string;
  url: string;
}

// 跟踪正在加载的图片ID
const loadingImages = ref<string[]>([]);

// 轮播图点击处理函数
function handleBannerClick(item: SwiperItem) {
  if (item.link) {
    uni.navigateTo({
      url: item.link,
    });
  }
}

// 图片加载完成处理函数
function onImageLoad(imageId?: string) {
  if (imageId && loadingImages.value.includes(imageId)) {
    loadingImages.value = loadingImages.value.filter((id) => id !== imageId);
  }
}

// 图片加载失败处理函数
function onImageError(imageId?: string) {
  if (imageId && loadingImages.value.includes(imageId)) {
    loadingImages.value = loadingImages.value.filter((id) => id !== imageId);
  }
}

// 加载家族统计数据
const loadFamilyStats = async () => {
  // TODO: 调用API获取家族统计数据
  familyStats.value = {
    familyCount: 10,
    memberCount: 100,
  };
};

// 将HTML富文本转换为纯文本
const htmlToText = (html: string): string => {
  if (!html) return "";
  return html.replace(/<[^>]+>/g, "");
};

// 加载最新文化内容
const loadCultureContents = async () => {
  try {
    const result = await CultureAPI.getCultureContentList({
      pageNum: "1",
      pageSize: "10",
    });

    // 处理富文本内容为纯文本
    cultureContents.value = result.list.map((item) => ({
      ...item,
      content: htmlToText(item.content),
    }));
  } catch (error) {
    console.error("获取文化内容失败", error);
  }
};

// 跳转到文化页面
const navigateToCulture = () => {
  uni.navigateTo({
    url: "/pages/work/culture/index",
  });
};

// 跳转到文化内容详情
const navigateToCultureDetail = (id: number) => {
  uni.navigateTo({
    url: `/pages/work/culture/detail?id=${id}`,
  });
};
// 获取推荐位内容列表
const getBannerImg = async () => {
  try {
    const result = await PositionContentAPI.getBannerList({
      categoryId: "15",
      pageNum: "1",
      pageSize: "10",
    });

    // 确保swiperList使用对象类型的数据
    swiperList.value = result.list
      .map((item: any) => ({
        id: item.id,
        image: item.image || "",
        link: item.link || "",
        title: item.title || "",
      }))
      .filter((item: SwiperItem) => item.image);
  } catch (error) {
    console.error("获取推荐位内容失败", error);
    // 添加默认图片以防没有数据时显示空白
    swiperList.value = [
      {
        image: "/static/images/default_banner.png",
      },
    ];
  }
};

// 获取推荐位tabs中的数据
const getNavList = async () => {
  try {
    // 清空现有数据，显示加载状态
    navList.splice(0, navList.length);

    const result = await PositionContentAPI.getBannerList({
      categoryId: "16",
      pageNum: "1",
      pageSize: "10",
    });
    // 检查返回数据是否有效
    if (result && result.list && Array.isArray(result.list) && result.list.length > 0) {
      // 清空现有数据
      navList.splice(0, navList.length);
      // 处理并添加新数据
      const processedList = result.list
        .map((item: any) => {
          const navId = item.id || `nav_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
          // 如果有图标，则添加到加载状态列表
          if (item.image) {
            loadingImages.value.push(navId);
          }
          return {
            id: navId,
            icon: item.image || "/static/icons/default.png",
            title: item.title || "未知标题",
            url: item.link || "",
          };
        })
        .filter((item: NavItem) => item.icon && item.title); // 过滤掉无效项

      // 将处理后的数据添加到navList中
      navList.push(...processedList);
    } else {
      // 如果API返回空数据，设置默认导航项
      setDefaultNavList();
    }
  } catch (error) {
    console.error("获取推荐位内容失败", error);
    // 错误情况下设置默认导航项
    setDefaultNavList();
  }
};

// 设置默认导航数据
function setDefaultNavList() {
  // 清空导航列表
  navList.value.splice(0, navList.value.length);

  const idPrefix = `default_${Date.now()}_`;
  const defaultNavs: NavItem[] = [];

  // 定义默认导航项配置
  const navConfigs = [
    {
      icon: "https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/a81d07a2cebc4a818f19141aa5de8a4f.png",
      title: "宗亲荟",
      url: "/pages/work/clan/clanList?type=all",
    },
    {
      icon: "https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/ef8122fd5d784c65b7d2f09fd9a12382.png",
      title: "捐赠榜",
      url: "/pages/work/donate/index",
    },
    {
      icon: "https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/b6ed80b424eb45379d75236eeae7b99b.png",
      title: "名人荟",
      url: "/pages/work/celebrity/index",
    },
    {
      icon: "https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/9a50cbcebef64101a9a84b80281595b6.png",
      title: "分布图",
      url: "/pages/work/map/index",
    },
    {
      icon: "https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/1014dc5532ae4e08b7dc8c70afeaa0ce.png",
      title: "家谱寻根",
      url: "/pages/genealogy/index",
    },
    {
      icon: "https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/181db7d645164e4cbc6ac4c744a175bd.png",
      title: "李氏宗祠",
      url: "/pages/work/family/list",
    },
    {
      icon: "https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/04915f6549894b91b86cc9190664b8d7.png",
      title: "三修基金",
      url: "/pages/work/fund/index",
    },
    {
      icon: "https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/3653453754f342878a8d635ef2f4b35c.png",
      title: "家族文化",
      url: "/pages/work/culture/index",
    },
  ];

  // 处理默认导航项并设置加载状态
  navConfigs.forEach((config) => {
    const fullId = idPrefix + config.id;
    // 将默认导航项的图片添加到加载状态列表
    loadingImages.value.push(fullId);

    defaultNavs.push({
      id: fullId,
      title: config.title,
      icon: config.icon,
      url: config.url,
    });
  });

  // 将处理后的默认导航项添加到navList
  navList.push(...defaultNavs);
}

onMounted(() => {
  loadFamilyStats();
  loadCultureContents();
  getBannerImg();
  getNavList();
});

// 分享给朋友
const onShareAppMessage = () => {
  return {
    title: "数字家谱系统 - 连接家族，传承文化",
    path: "/pages/index/index",
    // imageUrl: "/static/images/default_banner.png",
  };
};

// 分享到朋友圈
const onShareTimeline = () => {
  return {
    title: "数字家谱系统 - 连接家族，传承文化",
    query: "share=true",
    // imageUrl: "/static/images/default_banner.png",
  };
};

// 导出生命周期钩子
defineExpose({
  onShareAppMessage,
  onShareTimeline,
});
</script>

<style setup lang="scss">
@mixin text-ellipsis($line: 1) {
  @if $line == 1 {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  } @else {
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: $line;
    overflow: hidden;
  }
}

.home {
  padding: 10rpx 10rpx;
  padding-bottom: 50px;
  :deep(.custom-item) {
    height: 80px !important;
  }
  :deep(.wd-card) {
    margin: 10rpx 0 !important;
    padding-bottom: 10rpx;
  }
}

/* 轮播图样式 */
.banner-swiper {
  width: 100%;
  height: 400rpx;
  background-color: #f5f5f5;
  border-radius: 5px;
  overflow: hidden;
}

/* 导航列表空状态样式 */
.nav-empty {
  padding: 60rpx 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #f8f9fa;
  border-radius: 10rpx;
  margin: 10rpx 0;
}

.nav-empty image {
  animation: rotate 2s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 图片骨架屏样式 */
.image-skeleton {
  background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
  background-size: 200% 100%;
  animation: skeleton-loading 1.5s infinite;
}

@keyframes skeleton-loading {
  0% {
    background-position: 200% 0;
  }
  100% {
    background-position: -200% 0;
  }
}

.swiper-item {
  width: 100%;
  height: 100%;
  position: relative;
}

.swiper-image {
  width: 100%;
  height: 100%;
}

.swiper-title {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  padding: 20rpx;
  background-color: rgba(0, 0, 0, 0.5);
  color: #fff;
  font-size: 28rpx;
  box-sizing: border-box;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.card-title {
  font-size: 34rpx;
  font-weight: 500;
  color: #333;
}

.view-all-btn {
  border-radius: 30rpx;
  font-size: 24rpx;
}

.content-list {
  padding: 10rpx 0;
}

.content-item {
  padding: 20rpx;
  border-bottom: 1rpx solid #eee;

  &:last-child {
    border-bottom: none;
  }

  .content-info {
    .content-title {
      font-size: 32rpx;
      font-weight: 500;
      color: #333;
      margin-bottom: 12rpx;
    }

    .content-desc {
      font-size: 26rpx;
      color: #666;
      margin-bottom: 10rpx;
      line-height: 1.5;
    }

    .content-meta {
      display: flex;
      justify-content: space-between;
      font-size: 24rpx;
      color: #999;

      .author {
        color: #666;
      }

      .view-count {
        color: #999;
      }
    }
  }
}

.text-ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.text-ellipsis-2 {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.activity-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
.activity-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  margin-right: 10px;
}
.activity-nickname {
  font-weight: bold;
}
.activity-time {
  margin-left: 10px;
  color: #999;
  font-size: 12px;
}
.activity-title {
  font-size: 1rem;
  font-weight: bold;
  margin-bottom: 0.375rem;
  color: #333;
}
.activity-content {
  font-size: 0.875rem;
  color: #666;
  line-height: 1.5;
  margin-bottom: 0.5rem;
}
.post-images {
  display: flex;
  flex-wrap: wrap;
  margin: 0.5rem 0;
  position: relative;
  .post-image {
    width: calc((100% - 0.625rem) / 3);
    height: 6.875rem;
    margin-right: 0.3125rem;
    margin-bottom: 0.3125rem;
    border-radius: 0.25rem;
    -o-object-fit: cover;
    object-fit: cover;
  }
}
.activity-img {
  width: 100%;
  border-radius: 8px;
  margin-bottom: 10px;
}
.activity-footer {
  display: flex;
  justify-content: space-between;
  color: #999;
  font-size: 12px;
}
</style>
